import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage } from "element-plus"
import _config from './httpConfig'
import {removePending,addPending} from './pending'

const service = axios.create({
  baseURL: _config.baseURL,
  headers:_config.headers,
  withCredentials: true,
  timeout: _config.timeout,
  validateStatus() {
    // 使用async-await，处理reject情况较为繁琐，所以全部返回resolve，在业务代码中处理异常
    return true
  }
})

// 请求拦截器
service.interceptors.request.use((config: AxiosRequestConfig) => {
  removePending(config)
  addPending(config) 
  return config
}, (error) => {
  // 错误抛到业务代码
  return Promise.resolve(error)
})

// 响应拦截器
service.interceptors.response.use((response: AxiosResponse) => {
  const status = response.status
  return response
}, (error) => {
  if (axios.isCancel(error)) {
    console.log('repeated request: ' + error.message)
  } else {
    // handle error code
    // 错误抛到业务代码
    error.data = {}
    error.data.msg = '请求超时或服务器异常，请检查网络或联系管理员！'
    ElMessage.error(error.data.msg)
  }
  return Promise.reject(error)
})


// https://blog.csdn.net/liu19721018/article/details/115601515
export default service